<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Tailieu extends CI_Controller
{

	public	function __construct()
	{
		parent::__construct();
		if($this->session->userdata('user_id')){
			$this->load->helper("html");
			$this->load->model("tailieus");
			$this->load->model("giaobans");
			$this->load->model("users");
			$this->load->model("lich");
			$this->load->model("log_model");
			date_default_timezone_set('Asia/Ho_Chi_Minh');
		}
		else{
			redirect('login');
		}
	}
	///// view
	public function index($msg = null, $parameters = null)
	{
		$data['menu'] = "congvan";
		$data['list_tailieu'] = $this->tailieus->listTailieu();
		$data['list_giaoban'] = $this->giaobans->listGiaoban();
		$data['list_lich'] = $this->lich->listLich();
		/////////////
		$data['menu_tin'] = $this->giaobans->listGiaoban();
		$list = array();
		foreach ($data['menu_tin'] as $l){		//sap xep nhom danh sach theo giao ban cha
			if($l->id_type_giaoban != 9)
				$list[$l->cha_giaoban][] = $l;
		}
		
		$data['multi_menu_tin'] = $this->giaobans->multiGiaoban($list,0);						
		////////////
		$this->load->view('header_block_v1',$data);
		$this->load->view('content_sidebar_block',$data);
		switch ($msg){
			case null:
				$this->viewAllTailieu();
				break;
			case 'viewall':
				$this->viewAllTailieu($parameters);
				break;
			case 'viewadd':
				$this->viewAddTailieu($parameters);
				break;
			case 'viewedit':
				$this->viewEditTailieu($parameters);
				break;
			default:
				$this->viewAllTailieu();
				break;
		}
		
		$this->load->view('footer_block');
	}
	public function viewAllTailieu($type=null)
	{
		if($type==null){
			$data['list_tailieu'] = $this->tailieus->listTailieu();
			$this->load->view('tailieu/viewFolderTailieu',$data);
		}
		else{
			$data['checkQuyen'] = $this->kiemtraQuyen($type);
			$data['loai_tailieu'] = $this->tailieus->getTypeTailieu($type);
			$data['alltailieu'] = $this->tailieus->getAllTailieu($type);
			$data['type'] = $type;
			$this->load->view('tailieu/viewListTailieu',$data);
		}
	}
	
	public function viewAddTailieu($type=1)
	{
		if($this->kiemtraQuyen($type)) {
			$data['type'] = $type;
			$data['loai_tailieu'] = $this->tailieus->getTypeTailieu($type);
			$data['list_tailieu'] = $this->tailieus->listTailieu();
	
			$this->load->view('tailieu/viewAddTailieu',$data);
		}
		else
			redirect("tailieu");
	}
	public function viewEditTailieu($id_tailieu)
	{
		$data['tailieu'] = $this->tailieus->getTailieu($id_tailieu);
		if($this->kiemtraQuyen($data['tailieu']->loai_tailieu)) {
	
			$data['list_tailieu'] = $this->tailieus->listTailieu();
			$this->load->view('tailieu/viewEditTailieu',$data);
		}
		else{
			$this->viewAllTailieu();
		}
	}
	///// end view
	///// function
	public function download($id_tailieu)
	{
		//echo "dang download...";
		//các file upload được để trong 1 thư mục riêng
		$upload_dir = "./tailieufull/";
		//lấy tên file cần download từ URL
		$tailieu = $this->tailieus->getTailieu($id_tailieu);
		$name_tailieu = $tailieu->ten_tailieu;
		$filename = $tailieu->link_tailieu;
		$ext = explode('.', $filename);

		//thực hiện quá trình kiểm tra
		if (!is_file($upload_dir.$filename) || !is_readable($upload_dir.$filename) ) {
			///echo $upload_dir.$filename;
			echo "Loi: Ten file khong hop le hoac file khong ton tai!";
			exit(-1);
		} //end if
		$fp = fopen($upload_dir.$filename, "rb");
		//gởi header đến cho browser
		header('Content-type: application/octet-stream');
		if($ext[1] != '')
			header('Content-disposition: attachment; filename="'.$name_tailieu.'.'.$ext[1].'"');
		else
			header('Content-disposition: attachment; filename="'.$name_tailieu.'"');
		header('Content-length: ' . filesize($upload_dir.$filename));
		//đọc file và trả dữ liệu về cho browser
		fpassthru($fp);
		fclose($fp);
	}

	private function upload($userfile)
	{
		date_default_timezone_set('UTC');
		$create_date = date("YmdHis");

		$config['upload_path'] = './tailieufull/';
		$config['allowed_types'] = '*';
		$config['file_name'] = 'tailieus_'.$create_date;
		$config['overwrite'] = false;
		$config['max_size']	= '10048';			//<10MB
		//$config['max_width']  = '1024';			//<1024px
		//$config['max_height']  = '768';			//<768px

		$this->load->library('upload', $config);
		$this->upload->initialize($config);
		if(!$this->upload->do_upload($userfile))
		{
			$error = $this->upload->display_errors('', '');
			?>
<script type="text/javascript">	
			    				   		alert('<?php echo $error;?>');				   
			    					</script>
<?php	
$upload_data = $this->upload->data($userfile);
return null;			//loi
		}
		$upload_data = $this->upload->data($userfile);
			
		//print_r($upload_data);
			
		$news_img = $upload_data['file_name'];
		return $news_img;
	}

	public function kiemtraQuyen($type){
		if($this->users->checkQuyen(null,2,$type)){			//neu loai tai lieu nam trong ds gioi han quyen
			$quyen = $this->users->getQuyen($this->session->userdata("user_id"));
			$checkQuyen = FALSE;
			if($this->session->userdata("user_id") != 12 && $this->session->userdata("user_id") != 16){
				if(count($quyen) > 0){
					foreach($quyen as $q){
						if($this->users->checkQuyen($q->id_quyen,2,null)){
							$checkQuyen = TRUE;
							break;
						}
					}
				}
			}
			else
				$checkQuyen = TRUE;
			return $checkQuyen;
		}
		else{
			return TRUE;
		}
	}
	
	public function addTailieu()
	{
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		//dieu kien form
		$this->form_validation->set_rules('ten_tailieu', 'Tên tài liệu', 'xss_clean|required|min_length[5]');
		$this->form_validation->set_rules('mota_tailieu', 'Mô tả tài liệu', 'xss_clean|required|min_length[5]');
		$data["loai_tailieu"] = $this->input->post("loai_tailieu");
		
		if ($this->form_validation->run() == FALSE){			
			$this->index('viewadd',$data["loai_tailieu"]);
		}
		else {

			if($_FILES['upload_tailieu']['name'] == false)
				$data['link_tailieu'] = "";
			else
				$data['link_tailieu'] = $this->upload('upload_tailieu');
			$data["ten_tailieu"] = $this->input->post("ten_tailieu");
			$data["mota_tailieu"] = $this->input->post("mota_tailieu");
			
			if($this->kiemtraQuyen($data["loai_tailieu"])) {
				$url = base_url()."tailieu";
				if($this->tailieus->insertTailieu($data)){
					if($this->log_model->saveLog(3,null,null,"Tài liệu mới ".$data["ten_tailieu"]))
						echo "<script>alert('Bạn đã thêm 1 tài liệu mới');	window.location='".$url."'; </script>";
				}
				else
					echo "<script>alert('Lỗi: Không insert được!');	window.location='".$url."'; </script>";
			}
			else{
				echo "Lỗi: Không được quyền up loại file này!";
				//redirect('tailieu/viewadd/'.$data["loai_tailieu"]);
				$this->index('viewadd',$data["loai_tailieu"]);
			}
		}
	}

	public function editTailieu($id_tailieu)
	{
		$this->load->library('form_validation');
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		//dieu kien form
		$this->form_validation->set_rules('ten_tailieu', 'Tên tài liệu', 'xss_clean|required|min_length[5]');
		$this->form_validation->set_rules('mota_tailieu', 'Mô tả tài liệu', 'xss_clean|required|min_length[5]');
		if ($this->form_validation->run() == FALSE){
			$this->index('viewedit',$id_tailieu);
		}
		else {
			if($_FILES['upload_tailieu']['name'] != "")
				$data['link_tailieu'] = $this->upload('upload_tailieu');
			$data["ten_tailieu"] = $this->input->post("ten_tailieu");
			$data["mota_tailieu"] = $this->input->post("mota_tailieu");
			$data["loai_tailieu"] = $this->input->post("loai_tailieu");
			if($this->kiemtraQuyen($data["loai_tailieu"])) {
				$url = base_url()."tailieu";
				if($this->tailieus->editTailieu($id_tailieu,$data)){
					if($this->log_model->saveLog(4,null,null,"Tài liệu ".$data["ten_tailieu"]))
					echo "<script>alert('Bạn đã sửa tài liệu thành công');	window.location='".$url."'; </script>";
				}
				else
					echo "<script>alert('Lỗi: Không update được!');	window.location='".$url."'; </script>";
			}
			else{
				echo "<script>alert('Lỗi: Không được quyền up loại file này!');</script>";
				$this->editTailieu($id_tailieu);
			}
		}
	}

	public function delTailieu($id_tailieu)
	{
		$url = base_url()."tailieu";
		$tailieu = $this->tailieus->getTailieu($id_tailieu);
		$type_tailieu = $tailieu->loai_tailieu;
		if($this->kiemtraQuyen($type_tailieu)) {
			if($this->tailieus->delTailieu($id_tailieu)){
				if($this->log_model->saveLog(1,null,null,"Tài liệu ".$data["ten_tailieu"]))
				echo "<script>alert('Bạn đã xóa thành công');	window.location='".$url."'; </script>";
			}
			else
				echo "<script>alert('Lỗi: Không del được!');	window.location='".$url."'; </script>";
		}
		else{
				echo "<script>alert('Lỗi: Không được quyền up loại file này!');</script>";
				$this->index();
			}
	}


}